﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Xoohoo.Extensions;
using Xoohoo.Models;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Modules.Membership.ModelBinders
{
    public class UserInputEditModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            var valueProvider = bindingContext.ValueProvider;

            Guid userGroupID;
            if (String.IsNullOrEmpty(valueProvider.GetAttemptedValue("userGroupID")) || !valueProvider.GetAttemptedValue("userGroupID").GuidTryParse(out userGroupID))
                userGroupID = Guid.Empty;

            int? userID = null;
            int tmpUserID;
            string strUserID = bindingContext.ValueProvider.GetAttemptedValue("UserID");

            if (!strUserID.IsNullOrWhiteSpace()&&Int32.TryParse(strUserID, out tmpUserID))                
                userID = tmpUserID;

            string strStatus = valueProvider.GetAttemptedValue("status");
            UserStatus status = (UserStatus)Enum.Parse(typeof(UserStatus), strStatus, true);

            string username = valueProvider.GetAttemptedValue("username");
            string displayName = valueProvider.GetAttemptedValue("displayName");
            string email = valueProvider.GetAttemptedValue("email");
            string password = valueProvider.GetAttemptedValue("password");
            string passwordConfirm = valueProvider.GetAttemptedValue("passwordConfirm");
            //StringLength校验中，Empty字符串也将通不过校验
            password = password.IsNullOrEmpty() ? null : password;
            passwordConfirm = passwordConfirm.IsNullOrEmpty() ? null : passwordConfirm;

            var rolesValueProviderResult = valueProvider.GetValue("Roles");
            IEnumerable<Guid> roleIDList = ValueProviderResultToList(rolesValueProviderResult);

            var permissionsValueProviderResult = valueProvider.GetValue("Permissions");
            IEnumerable<Guid> permissionIDList = ValueProviderResultToList(permissionsValueProviderResult);

            return new UserInputEdit(userID, userGroupID, status, username, displayName, email, password, passwordConfirm, roleIDList, permissionIDList);
        }
        private IEnumerable<Guid> ValueProviderResultToList(ValueProviderResult valueProviderResult)
        {
            if (valueProviderResult != null)
            {
                string[] array = valueProviderResult.RawValue as string[];
                if (array != null)
                {
                    return from s in array
                           where s.IsGuid()
                           select new Guid(s);
                }
            }
            return Enumerable.Empty<Guid>();
        }
    }
}
